h<template>
  <div class="detail">
    <el-steps :active="step" finish-status="success">
      <el-step title="商品基本信息" />
      <el-step title="添加库存信息" />
      <el-step title="添加移动端详情" />
    </el-steps>

    <el-card shadow="never" class="margin-30">
      <el-form ref="goodsForm" :model="goods" :rules="rules" label-width="80px" size="mini">

        <div v-show="step==1">
          <div class="common-title">
            <h4>基本信息</h4>
            <el-divider />
          </div>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="goods.name" placeholder="商品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品编码">
                <el-input v-model="goods.productSn" placeholder="商品编码" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item v-if="categoryList && categoryList.length" label="商品分类">
                <el-select v-model="goods.productCategoryId" style="width:100%" placeholder="商品分类" clearable>
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>

              </el-form-item>
            </el-col>
          </el-row>
          <div class="common-title">
            <h4>商品属性</h4>
            <el-divider />
          </div>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="商品原价">
                <el-input-number v-model="goods.originalPrice" style="width:100%" placeholder="商品原价" :step="5" :min="0" />
                <!-- <el-input-number v-model="" size="normal" label=""
                  :min="1" :max="10" :step="1" :controls="true" controls-position="both" @change="">
                </el-input-number> -->

              </el-form-item>

            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="促销类型">
                <!--  // 促销类型：0->没有促销使用原价;1->使用促销价；2->使用会员价；3->使用阶梯价格；4->使用满减价格；5->限时购 ,promotionType -->
                <el-select v-model="goods.promotionType" disabled style="width:100%" placeholder="促销类型" clearable>
                  <el-option
                    v-for="item in promotionType"
                    :key="item.id"
                    :label="item.text"
                    :value="item.value"
                  />
                </el-select>

              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="活动价格">
                <el-input-number v-model="goods.promotionPrice" disabled style="width:100%" placeholder="活动价格" :step="5" :min="0" />

              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0" />
            <el-col :span="12" :offset="0" />
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0" />
            <el-col :span="12" :offset="0" />
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="缩略图">
                <el-upload
                  ref="coverImgRef"
                  class="avatar-uploader"
                  :action="uploadFileOss"
                  :on-success="handleCoverImgSuccess"
                  :before-upload="beforeCoverImgUpload"
                  :headers="token"
                >
                  <img v-if="goods.pic" :src="goods.pic" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>

              </el-form-item>
            </el-col>

          </el-row>
          <div class="common-title">
            <h4>商其他信息品属性</h4>
            <el-divider />
          </div>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0" />
            <el-col :span="12" :offset="0" />
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0" />
            <el-col :span="12" :offset="0" />
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="产品服务">
                <!-- //  以逗号分割的产品服务：1->无忧退货；2->快速退款；3->免费包邮 ,
                  'serviceIds': 'string', // 1,2
                -->
                <el-checkbox-group v-model="goods.checkServiceList">
                  <el-checkbox label="1">无忧退货</el-checkbox>
                  <el-checkbox label="2">快速退款</el-checkbox>
                  <el-checkbox label="3">免费包邮</el-checkbox>
                </el-checkbox-group>
              </el-form-item>

            </el-col>

          </el-row>

        </div>
        <div v-show="step==2">
          <div class="common-title">
            <h4>商品sku信息</h4>
            <el-divider />
          </div>
          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="标题" prop="detailTitle">
                <el-input v-model="goods.detailTitle" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="副标题">
                <el-input />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="画册图片">
                <el-upload
                  ref="albumPicsUpload"
                  :action="uploadFileOss"
                  list-type="picture-card"
                  :headers="token"
                  :on-success="albumPicsUploadSucc"
                >
                  <i slot="default" class="el-icon-plus" />
                  <div slot="file" slot-scope="{file}">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    >
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <i class="el-icon-zoom-in" />
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleDownload(file)"
                      >
                        <i class="el-icon-download" />
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                      >
                        <i class="el-icon-delete" />
                      </span>
                    </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="20">
            <el-col :span="24" :offset="0">
              <el-form-item label="sku设置">
                <div>
                  <span>颜色:</span>
                  <el-checkbox-group v-model="skuColorTemp.skuSelectedList" style="display:inline-block;margin-left: 10px;">
                    <el-checkbox v-for="color in skuColorTemp.skuList" :key="color" :label="color">
                      {{ color }}
                      <el-button type="text" size="mini" style="color:red;padding-left: 10px;" @click="deleteOption('color',color)">删除</el-button>

                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <div>
                  <span>大小:</span>
                  <el-checkbox-group v-model="skuSizeTemp.skuSelectedList" style="display:inline-block;margin-left: 10px;">
                    <el-checkbox v-for="size in skuSizeTemp.skuList" :key="size" :label="size">
                      {{ size }}
                      <el-button type="text" size="mini" style="color:red;padding-left: 10px;" @click="deleteOption('size',size)">删除</el-button>

                    </el-checkbox>
                  </el-checkbox-group>
                </div>

                <div>
                  <el-input v-model="skuColorTemp.text" style="width:200px;" placeholder="颜色：土豪金" size="mini" clearable />
                  <el-button type="defalut" size="mini" style="margin-left:30px;" @click="createOption('color')">创建颜色选项</el-button>
                  <el-input v-model="skuSizeTemp.text" style="width:200px;margin-left:30px;" placeholder="大小：128g" size="mini" clearable />
                  <el-button type="defalut" size="mini" style="margin-left:30px;" @click="createOption('size')">创建大小选项</el-button>
                  <el-button type="primary" size="mini" style="margin-left:100px;" @click="createSkuList">生成sku列表</el-button>
                  <el-button type="primary" size="mini" style="margin-left:100px;" @click="addSkuOption">新增sku</el-button>
                </div>

                <!-- sku列表 -->
                <el-table v-if="tempPmsSkuStockList.length" :data="tempPmsSkuStockList" border stripe>
                  <el-table-column
                    type="index"
                    align="center"
                    label="#"
                    width="50"
                  />
                  <el-table-column

                    align="center"
                    label="图片"
                    width="100"
                  >
                    <template slot-scope="scope">
                      <el-upload
                        :ref="`upload_${scope.row.tempId}`"
                        :action="uploadFileOss"
                        :on-success="skuImgUploadSucc"
                        :headers="token"

                        @click.native="saveTempId(scope.row.tempId)"
                      >
                        <el-button v-if="!scope.row.pic" slot="trigger" size="mni" type="primary">+</el-button>
                        <img v-else width="80" height="80" :src="scope.row.pic" alt="">
                        <!-- <div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div> -->
                      </el-upload>

                    </template>

                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="颜色"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.color" size="mini" clearable />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="大小"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.size" size="mini" clearable />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="库存"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.stock" size="mini" clearable />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="库存警戒"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.lowStock" size="mini" clearable />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="锁定库存"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.lockStock" size="mini" clearable />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="sku编码"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.skuCode" size="mini" clearable />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="价格"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.price" size="mini" clearable />
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="销量"
                    width="200"
                  >
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.sale" size="mini" clearable />
                    </template>
                  </el-table-column>
                  <el-table-column
                    fixed="right"
                    align="center"
                    label="操作"
                    width="200"
                  >
                    <template>
                      <el-button type="text" size="mini" style="color:red">删除</el-button>

                    </template>
                  </el-table-column>
                </el-table>

              </el-form-item>
            </el-col>

          </el-row>

        </div>
        <div v-show="step==3">
          <div class="common-title">
            <h4>详情描述</h4>
            <el-divider />
          </div>
        </div>
        <el-form-item>
          <el-button v-if="step!=1" type="default" @click="preStep">返回上一步</el-button>
          <el-button v-if="step!=3" type="primary" @click="nextStep">
            {{ step==1?'下一步,填写库存信息 ':step==2?'下一步,填写移动端详情 ':'' }}
          </el-button>

          <el-button v-if="step==3" type="primary" size="mini" @click="doAddProduct">提交保存</el-button>

        </el-form-item>
      </el-form>

    </el-card>

  </div>
</template>
<script>
import mix from '@/mixins/index'
import { v4 as uuidv4 } from 'uuid'
import {
  getAllCategory as getAllCategoryApi,
  addProductAndSkus as addProductAndSkusApi
} from '@/api/product/list'
export default {
  name: 'ProductDetail',
  mixins: [mix],
  data() {
    return {
      step: 1,
      rules: {
        name: [{ required: true, message: '商品名称必填', trigger: 'blur' }],
        detailTitle: [{ required: true, message: '商品标题必填', trigger: 'blur' }]
      },
      goods: {
        pic: '',
        checkServiceList: []
      },
      // 0->没有促销使用原价;1->使用促销价；2->使用会员价；3->使用阶梯价格；4->使用满减价格；5->限时购
      promotionType: [
        {
          id: 1,
          text: '没有促销使用原价',
          value: 0
        },

        {
          id: 2,
          text: '使用促销价',
          value: 1
        },
        {
          id: 3,
          text: '使用会员价',
          value: 2
        },
        {
          id: 4,
          text: '使用阶梯价格',
          value: 3
        },
        {
          id: 5,
          text: '使用满减价格',
          value: 4
        },
        {
          id: 6,
          text: '限时购 ',
          value: 5
        }

      ],
      onePageParams: ['name'], // 第一页校验字段
      secondPageParams: ['detailTitle'], // 第二页校验字段
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      albumPicsFileList: [],
      skuColorTemp: {
        text: '',
        skuList: ['土豪金', '天空蓝'],
        skuSelectedList: ['土豪金', '天空蓝']
      },
      skuSizeTemp: {
        text: '',
        skuList: ['128g', '64g'],
        skuSelectedList: ['128g', '64g']
      },
      tempPmsSkuStockList: [], // sku 列表
      tempId: '', // 临时tempid
      categoryList: []

    }
  },
  computed: {
  },
  watch: {
  },
  created() {
    this.getCategoryList()
  },
  mounted() {
  },
  methods: {
    async getCategoryList() {
      const res = await getAllCategoryApi()
      const { success, data, message } = res
      if (success) {
        this.categoryList = data.items.find(ele => ele.category.name === '乐居').children
      } else {
        this.$message.error(message)
      }
    },
    // sku 创建选项 大小 颜色
    createOption(type) {
      if (type === 'size') {
        // 1. 先判断 skuList 是否存在 输入框输入的值 text
        if (this.skuSizeTemp.skuList.indexOf(this.skuSizeTemp.text) > -1) {
          this.$message.warning(`${this.skuSizeTemp.text}已存在`)
        } else {
          this.skuSizeTemp.skuList.push(this.skuSizeTemp.text)
        }
        this.skuSizeTemp.text = ''
      } else {
        if (this.skuColorTemp.skuList.indexOf(this.skuColorTemp.text) > -1) {
          this.$message.warning(`${this.skuColorTemp.text}已存在`)
        } else {
          this.skuColorTemp.skuList.push(this.skuColorTemp.text)
        }
        this.skuColorTemp.text = ''
      }
    },
    // sku 删除选项 大小 颜色
    deleteOption(type, item) {
      if (type === 'color') {
        // 适合处理大量数据
        // const index = this.skuColorTemp.skuList.findIndex(ele => ele === item)
        // if (index > -1) {
        //   this.skuColorTemp.skuList.splice(index, 1)
        // }
        // 使用少量数据
        this.skuColorTemp.skuList = this.skuColorTemp.skuList.filter(ele => ele !== item)
      } else {
        this.skuSizeTemp.skuList = this.skuSizeTemp.skuList.filter(ele => ele !== item)
      }
    },
    // 生成sku列表
    createSkuList() {
      for (let i = 0; i < this.skuColorTemp.skuSelectedList.length; i++) {
        for (let j = 0; j < this.skuSizeTemp.skuSelectedList.length; j++) {
          this.tempPmsSkuStockList.push({
            'tempId': uuidv4(), // 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
            'lockStock': 5, // 锁定库存
            'lowStock': 10, // 库存警戒线
            'pic': '', // 图片
            'price': 499900, // 当前价格,单位是   分
            'promotionPrice': 0, // 单品促销价格
            'sale': 0, // 销量
            'skuCode': '', // sku的编码,手动填写
            // spData:  [{"key":"颜色","value":"蓝色"},{"key":"容量","value":"32G"}]
            // 'spData': 'string', // sku属性，json格式String类型 ,
            'stock': 1000, // 库存
            'size': this.skuSizeTemp.skuSelectedList[j],
            'color': this.skuColorTemp.skuSelectedList[i]
          })
        }
      }
    },
    // 新增sku
    addSkuOption() {

    },
    // sku 图片上传成功
    skuImgUploadSucc(res) {
      const { success, data, message } = res
      if (success) {
        const item = this.tempPmsSkuStockList.find(ele => ele.tempId === this.tempId)
        if (item) {
          item.pic = data.fileUrl

          // 1. 删除上传列表条
          this.$refs[`upload_${this.tempId}`].clearFiles()
          // 2. tempId 清空
          this.tempId = ''
        }
      } else {
        this.$message.error(message)
      }
    },
    //  sku 图片上传保存临时的tempID
    saveTempId(tempid) {
      // console.log('tempid===>', tempid)
      this.tempId = tempid
    },
    albumPicsUploadSucc(res, file, fileList) {
      console.log('res==>', res)
      console.log('file==>', file)
      console.log('fileList==>', fileList)
      this.goods.albumPics = fileList.map(file => {
        return file.response.data.fileUrl
      }).join(',')
      this.albumPicsFileList = fileList
      console.log('this.goods.albumPics==>', this.goods.albumPics)
    },
    handleRemove(file) {
      // console.log(file)

      // console.log(this.$refs.albumPicsUpload.fileList)
      // console.log(this.$refs.albumPicsUpload)
      const index = this.albumPicsFileList.findIndex(ele => ele.uid === file.uid)
      this.albumPicsFileList.splice(index, 1)
      console.log('this.albumPicsFileList==>', this.albumPicsFileList)
      this.goods.albumPics = this.albumPicsFileList.map(file => {
        return file.response.data.fileUrl
      }).join(',')
      console.log('this.goods.albumPics==>', this.goods.albumPics)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      console.log(file)
    },
    nextStep() {
      // this.step += 1
      var valid = true
      let validArr = []
      if (this.step === 1) {
        validArr = this.onePageParams
      } else if (this.step === 2) {
        validArr = this.secondPageParams
      }
      this.$refs.goodsForm.validateField(validArr, (err) => {
        console.log('err======>', err)
        if (err) {
          // console.log(err)
          valid = valid && false
        } else {
          // this.step += 1
          valid = valid && true
        }
      })

      if (valid) {
        this.step += 1
      }
    },
    preStep() {
      this.step -= 1
    },

    // 提交保存
    async doAddProduct() {
      // const product = {}
      // product.product = this.goods
      // product.pmsSkuStockList = this.tempPmsSkuStockList
      // console.log(product)
      var pmsSkuList = []
      this.tempPmsSkuStockList.forEach(ele => {
        pmsSkuList.push(
          {
            ...ele,
            // spData:  [{"key":"颜色","value":"蓝色"},{"key":"容量","value":"32G"}]
            'spData': JSON.stringify([
              {
                key: '颜色',
                value: ele.color
              },
              {
                key: '容量',
                value: ele.size
              }

            ])
          }
        )
      })
      var product = {
        'pmsSkuStockList': pmsSkuList,
        'product': {
          'albumPics': 'https://img12.360buyimg.com/n7/jfs/t1/17004/6/18505/101023/632930d9E3d327c0a/8496c32bf6bb6a99.jpg,https://img14.360buyimg.com/n7/jfs/t1/105905/22/33633/64597/63297ef3E6d91a62b/d6de870240bbf35a.jpg', // 画册图片，连产品图片限制为5张，以逗号分割 ,会在移动端商品详情页展示
          'brandId': '1329320162080423937', // 关联的 品牌id
          'brandName': '东易日盛家居装饰', // 品牌名称

          'description': '意式极简北欧轻奢卧室电视柜高款现代北欧储物柜小户型精品家具 卧室电视柜（两门）', // 意式极简北欧轻奢卧室电视柜高款现代北欧储物柜小户型精品家具 卧室电视柜（两门）
          // detail是进入详情页展示的内容
          'detailDesc': ' 家具新品大赏：1件7.5折，2件7.2折，满额在享2%现金返现，超值好礼送不停', // 副标题 家具新品大赏：1件7.5折，2件7.2折，满额在享2%现金返现，超值好礼送不停！时间：11.14-11.20

          'detailMobileHtml': '<h1>detailMobileHtml</h1>', // 移动端展示方式,商品的富文本内容,放到这个字段
          'detailTitle': '简野 电视柜 意式极简北欧轻奢卧室电视柜高款现代北欧储物柜小户型精品家具 卧室电视柜（两门）', // 标题 简野 电视柜 意式极简北欧轻奢卧室电视柜高款现代北欧储物柜小户型精品家具 卧室电视柜（两门）

          'keywords': '地中海,凳子', // 关键词,逗号分割,  地中海,凳子,xxx
          'lowStock': 10, // 预警库存(预留)

          'name': '华为手机', // 商品名称 简野（JIANYE）ZY-22
          'newStatus': 1, // 新品状态:0->不是新品；1->新品 ,新品会在移动端首页推荐
          'note': '小舅子供货不入账 ', // 备注,比如小舅子供货不入账 ,
          'originalPrice': 66666, // 原价
          'pic': 'https://img12.360buyimg.com/n7/jfs/t1/123362/15/29729/64701/63295e32Ee4113e63/8a0a76d4c801fb3a.jpg', // 封面图片
          'previewStatus': 0, // 是否为预告商品：0->不是；1->是 ,
          'price': 66665, // 当前价格

          'productCategoryId': '1308339256886423554', // 分类id
          'productCategoryName': '创意', // 分类名称
          'productSn': '33333', // 商品编码,需要手填.
          // 促销类型：0->没有促销使用原价;1->使用促销价；2->使用会员价；3->使用阶梯价格；4->使用满减价格；5->限时购 ,
          'promotionType': 0,
          // 上架状态：0->下架；1->上架 ,
          'publishStatus': 1,
          // 推荐状态；0->不推荐；1->推荐 ,
          'recommendStatus': 1,
          // 销量,不用处理
          'sale': 0,
          //  以逗号分割的产品服务：1->无忧退货；2->快速退款；3->免费包邮 ,
          'serviceIds': '1,2', // 1,2
          'sort': 999999, // 排序,降序.值越大越靠前
          'stock': 100, // 库存
          'subTitle': '二级标题', // 二级标题
          'unit': '台', // 单位,比如 斤/辆/台

          'verifyStatus': 1, //  审核状态：0->未审核；1->审核通过 ,
          'weight': 0.1 // 商品重量，默认为千克
        }
      }

      // console.log(product)
      const res = await addProductAndSkusApi(product)
      console.log(res)
    },
    handleCoverImgSuccess(res) {
      const { success, data, message } = res
      if (success) {
        this.goods.pic = data.fileUrl
        this.$refs.coverImgRef.clearFiles()
      } else {
        this.$message.error(message)
      }
    },
    beforeCoverImgUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style lang="scss" scoped>
  .detail{
    .el-steps{
      padding: 50px 300px;
      background-color: #fff;
    }
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  }
</style>
